﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceWarranty;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.CustomerService.Controllers
{
    public class InMaintainWorkOrderController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        #region 获取报案工单任务列表数据
        /// <summary>
        /// 获取报案工单任务列表数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Index(InsuranceWarrantyRecordModel model)
        {
            var total = 0;
            var list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total).Include(o => o.SystemUser).Include(o => o.InsuranceOrder).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.InsuranceOrderId,
                o.WarrantyRecordNo,
                o.Reporter,
                o.ReporterPhone,
                o.Status,
                StatusDesc = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetStatusName(o.Status),
                o.CreateTime,
                o.LastModifyTime,
                o.InsuranceOrder.InsuranceCompany,
                o.InsuranceOrder.InsuranceCompanyBranch,
                o.ServiceProviderBranch.ServiceProvider.ServiceProviderName,
                AccessoriesType = "维修配件",
                WarrantyMaintenanceType = EnumHelper.Instance.GetDescription(typeof(WarrantyMaintenanceType), o.WarrantyMaintenanceTypeID),
                o.SortingCenterSendOrderUserID,
                SendOrderTime = o.SendOrderTime.HasValue ? o.SendOrderTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",

            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion
        public ActionResult Detail(int id)
        {
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id);
            return View(insuranceWarrantyRecord);
        }
        public ActionResult SendOrderAgain(int id)
        {
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id);
            return View(insuranceWarrantyRecord);
        }


        #region 完成维修
        [HttpPost]
        [ValidateInput(true)]
        public ActionResult SaveCompleteMaintainInsuranceWarrantyRecord(InsuranceWarrantyRecord model, InsuranceWarrantyRecordExpressInfo insuranceWarrantyRecordExpressInfo, IList<InsuranceWarrantyRecordAuditInfo> insuranceWarrantyRecordAuditInfo, List<InsuranceWarrantyRecordAccessories> insuranceWarrantyRecordAccessories, int saveType)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Save
            };

            var warrantyRecordService = ServiceFactory.InsuranceWarrantyRecordServiceInstance;
            var auditInfoService = ServiceFactory.InsuranceWarrantyRecordAuditInfoServiceInstance;

            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    var entity = warrantyRecordService.LoadByID(model.ID);
                    if (saveType == 2)
                    {
                        entity.Status = (byte)InsuranceWarrantyStatus.Close;
                        entity.LastModifyBy = CurrentUser.UserAccount;
                        entity.LastModifyTime = DateTime.Now;
                        if (model.Status != entity.Status)
                        {
                            //获取父级状态
                            var service = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance;
                            InsuranceWarrantyRecordStatus newStatusInfo =
                                service.LoadEntities(t => t.StatusCode == entity.Status).FirstOrDefault();

                            //记录流程日志
                            InsuranceWarrantyRecordStatus oldStatusInfo =
                                service.LoadEntities(t => t.StatusCode == model.Status).FirstOrDefault();
                            var insuranceWarrantyRecordController = new InsuranceWarrantyRecordController();
                            insuranceWarrantyRecordController.WriteProcessLog(oldStatusInfo, newStatusInfo, null,
                                model.ID);

                            responseResult.Success = warrantyRecordService.UpdateEntities(entity);
                        }
                    }
                    if (saveType == 1 || responseResult.Success)
                    {
                        if (insuranceWarrantyRecordAuditInfo != null && insuranceWarrantyRecordAuditInfo.Any())//保存审核信息
                            responseResult.Success = auditInfoService.Save(model.ID, insuranceWarrantyRecordAuditInfo,
                                CurrentUser.UserAccount);
                        if (insuranceWarrantyRecordAccessories != null && insuranceWarrantyRecordAccessories.Any()) //保存维修详情
                        {
                            insuranceWarrantyRecordAccessories.ForEach(o => o.InsuranceWarrantyRecordID = model.ID);
                            responseResult.Success =
                                ServiceFactory.InsuranceWarrantyRecordAccessoriesServiceInstance.Save(
                                    insuranceWarrantyRecordAccessories, CurrentUser.UserAccount);
                        }
                    }
                    if (responseResult.Success)
                    {
                        var expressInfoService = ServiceFactory.InsuranceWarrantyRecordExpressInfoServiceInstance;
                        var expressInfoEntity = expressInfoService.Load(model.ID,
                            (byte)ExpressSendByWhoType.RepairCenterSendToUser);
                        if (expressInfoEntity != null)
                        {
                            expressInfoEntity.ExpressSendByWhoType = (byte)ExpressSendByWhoType.RepairCenterSendToUser;
                            expressInfoEntity.ExpressCompanyID = insuranceWarrantyRecordExpressInfo.ExpressCompanyID;
                            expressInfoEntity.ExpressNo = insuranceWarrantyRecordExpressInfo.ExpressNo ?? "";
                            expressInfoEntity.ExpressStatus = insuranceWarrantyRecordExpressInfo.ExpressStatus;
                            expressInfoEntity.SendUserPhone = insuranceWarrantyRecordExpressInfo.SendUserPhone ?? "";
                            expressInfoEntity.SendUserName = insuranceWarrantyRecordExpressInfo.SendUserName ?? "";
                            expressInfoEntity.SendUserAddress = insuranceWarrantyRecordExpressInfo.SendUserAddress;
                            expressInfoEntity.ExpressPrice = insuranceWarrantyRecordExpressInfo.ExpressPrice;
                            expressInfoEntity.ReceiverUserPhone = insuranceWarrantyRecordExpressInfo.ReceiverUserPhone ?? "";
                            expressInfoEntity.ReceiverUserName = insuranceWarrantyRecordExpressInfo.ReceiverUserName ?? "";
                            expressInfoEntity.ReceiverUserAddress = insuranceWarrantyRecordExpressInfo.ReceiverUserAddress ?? "";
                            expressInfoEntity.PickUpExpressManName = insuranceWarrantyRecordExpressInfo.PickUpExpressManName;
                            expressInfoEntity.PickUpExpressManPhone = insuranceWarrantyRecordExpressInfo.PickUpExpressManPhone;
                            responseResult.Success = expressInfoService.UpdateEntities(expressInfoEntity);
                        }
                        else
                        {
                            insuranceWarrantyRecordExpressInfo.ID = 0;
                            insuranceWarrantyRecordExpressInfo.ExpressSendByWhoType = (byte)ExpressSendByWhoType.RepairCenterSendToUser;
                            insuranceWarrantyRecordExpressInfo.InsuranceWarrantyRecordID = model.ID;
                            insuranceWarrantyRecordExpressInfo.CreatedBy = CurrentUser.UserAccount;
                            insuranceWarrantyRecordExpressInfo.CreatedTime = DateTime.Now;
                            responseResult.Success = expressInfoService.AddEntities(insuranceWarrantyRecordExpressInfo).ID > 0;
                        }
                    }
                    if (responseResult.Success)
                    {
                        ts.Complete();
                    }
                    else
                    {
                        ts.Dispose();
                    }
                }
                catch (Exception e)
                {
                    ts.Dispose();
                }
            }
            return Json(responseResult);
        }
        #endregion

        #region 保存重新派单
        [HttpPost]
        [ValidateInput(true)]
        public ActionResult SaveSendOrderAgain(InsuranceWarrantyRecord model, InsuranceWarrantyRecordExpressInfo insuranceWarrantyRecordExpressInfo, InsuranceWarrantyRecordAccessories insuranceWarrantyRecordAccessories)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Save
            };

            var warrantyRecordService = ServiceFactory.InsuranceWarrantyRecordServiceInstance;
            var auditInfoService = ServiceFactory.InsuranceWarrantyRecordAuditInfoServiceInstance;
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    var entity = warrantyRecordService.LoadByID(model.ID);
                    entity.AccidentAddress = model.AccidentAddress;
                    entity.SortingCenterSendOrderUserID = CurrentUser.ID;//派单人
                    entity.SendOrderTime = DateTime.Now;
                    entity.LastModifyTime = DateTime.Now;
                    entity.LastModifyBy = CurrentUser.UserAccount;

                    #region 记录修改派单信息
                    var opreateLogs = new OpreateLogs
                    {
                        CreatedTime = DateTime.Now,
                        LogTableName = "InsuranceWarrantyRecord",
                        LogSubject = "修改派单信息",
                        LogTablePKID = entity.ID,
                        OpreateUserAccount = CurrentUser.UserAccount,
                        OpreateUserName = CurrentUser.UserDisPlayName
                    };
                    var logEntity = new
                    {
                        entity.SortingCenterSendOrderUserID,
                        entity.SendOrderTime,
                        entity.AccidentAddress,
                    };
                    var addLogResult = ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, logEntity, model);
                    #endregion
                    #region 原来是分拣寄修，只需要改变维修网点
                    if (entity.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.SendRevised)
                    {
                        if (!model.ServiceProviderBranchId.HasValue)
                        {
                            responseResult.Message = "请选择维修服务商！";
                        }
                        else
                        {
                            entity.ServiceProviderBranchId = model.ServiceProviderBranchId;
                            responseResult.Success = warrantyRecordService.UpdateEntities(entity);
                            #region 修改维修服务商
                            opreateLogs = new OpreateLogs
                            {
                                CreatedTime = DateTime.Now,
                                LogTableName = "InsuranceWarrantyRecord",
                                LogSubject = "修改维修服务商",
                                LogTablePKID = entity.ID,
                                OpreateUserAccount = CurrentUser.UserAccount,
                                OpreateUserName = CurrentUser.UserDisPlayName
                            };
                            var logEntity1 = new
                            {
                                entity.ServiceProviderBranchId,
                            };
                            ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, logEntity1, model);
                            #endregion
                        }
                    }
                    #endregion
                    #region 原工单非寄修
                    else
                    {
                        if (model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.SendRevised)
                        {
                            entity.SortingCenterID = model.SortingCenterID;//必须选择分拣中心
                            entity.SortingRemark = model.SortingRemark;
                            entity.Status = (byte)InsuranceWarrantyStatus.EquipmentInSorting;
                            #region 修改维修服务商
                            opreateLogs = new OpreateLogs
                            {
                                CreatedTime = DateTime.Now,
                                LogTableName = "InsuranceWarrantyRecord",
                                LogSubject = "重新派单修改分拣中心",
                                LogTablePKID = entity.ID,
                                OpreateUserAccount = CurrentUser.UserAccount,
                                OpreateUserName = CurrentUser.UserDisPlayName
                            };
                            var logEntity1 = new
                            {
                                entity.SortingCenterID,
                                entity.SortingRemark,
                            };
                            ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, logEntity1, model);
                            #endregion
                        }
                        //到店、上门
                        else if (model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.OnsiteRepair || model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.ShopRepair)
                        {
                            entity.ServiceProviderBranchId = model.ServiceProviderBranchId;
                            entity.Status = model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.OnsiteRepair ? (byte)InsuranceWarrantyStatus.HomeMaintenance : (byte)InsuranceWarrantyStatus.HaveArrangeToStore;
                            entity.UserWarrantyRemark = model.UserWarrantyRemark;

                            #region 修改维修服务商
                            opreateLogs = new OpreateLogs
                            {
                                CreatedTime = DateTime.Now,
                                LogTableName = "InsuranceWarrantyRecord",
                                LogSubject = "重新派单修改维修服务商",
                                LogTablePKID = entity.ID,
                                OpreateUserAccount = CurrentUser.UserAccount,
                                OpreateUserName = CurrentUser.UserDisPlayName
                            };
                            var logEntity1 = new
                            {
                                entity.ServiceProviderBranchId,
                                entity.UserWarrantyRemark,
                            };
                            ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, logEntity1, model);
                            #endregion
                        }
                        else//官修
                        {
                            entity.Status = (byte)InsuranceWarrantyStatus.OfficialRepair;
                            entity.UserWarrantyRemark = model.UserWarrantyRemark;
                        }

                        entity.WarrantyMaintenanceTypeID = model.WarrantyMaintenanceTypeID;

                        if (model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.SendRevised && !model.SortingCenterID.HasValue)
                        {
                            responseResult.Message = "分拣寄修必须选择分拣中心！";
                        }
                        else if ((model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.OnsiteRepair || model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.ShopRepair) &&
                                 !model.ServiceProviderBranchId.HasValue)
                        {
                            responseResult.Message = "上门维修或到店维修必须选择维修服务商！";
                        }
                        else
                        {
                            responseResult.Success = warrantyRecordService.UpdateEntities(entity);
                            #region 记录状态修改日志
                            if (entity.Status != model.Status)
                            {
                                //获取父级状态
                                var service = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance;
                                InsuranceWarrantyRecordStatus newStatusInfo = service.LoadEntities(t => t.StatusCode == entity.Status).FirstOrDefault();

                                //记录流程日志
                                InsuranceWarrantyRecordStatus oldStatusInfo = service.LoadEntities(t => t.StatusCode == model.Status).FirstOrDefault();
                                var insuranceWarrantyRecordController = new InsuranceWarrantyRecordController();
                                insuranceWarrantyRecordController.WriteProcessLog(oldStatusInfo, newStatusInfo, null, model.ID);
                            }
                            #endregion
                            if (responseResult.Success)
                            {
                                if (insuranceWarrantyRecordAccessories != null &&
                                    insuranceWarrantyRecordAccessories.AccessoriesTypeID > 0 &&
                                    insuranceWarrantyRecordAccessories.AccessoriesLevelID > 0)//保存维修配件\暂时只允许维修一个
                                {
                                    var insuranceWarrantyRecordAccessoriesList =
                                        new List<InsuranceWarrantyRecordAccessories>() { insuranceWarrantyRecordAccessories };
                                    responseResult.Success =
                                        ServiceFactory.InsuranceWarrantyRecordAccessoriesServiceInstance.Save(
                                            insuranceWarrantyRecordAccessoriesList, CurrentUser.UserAccount);
                                }
                                if (responseResult.Success)
                                {
                                    if (model.WarrantyMaintenanceTypeID == (byte)WarrantyMaintenanceType.SendRevised)//分拣寄修保存快递信息
                                    {
                                        var expressInfoService = ServiceFactory.InsuranceWarrantyRecordExpressInfoServiceInstance;
                                        var expressInfoEntity = expressInfoService.Load(model.ID,
                                            (byte)ExpressSendByWhoType.UserSendToPartitionCenter);
                                        if (expressInfoEntity != null)
                                        {
                                            expressInfoEntity.ExpressSendByWhoType = (byte)ExpressSendByWhoType.UserSendToPartitionCenter;
                                            expressInfoEntity.ExpressCompanyID = insuranceWarrantyRecordExpressInfo.ExpressCompanyID;
                                            expressInfoEntity.ExpressNo = insuranceWarrantyRecordExpressInfo.ExpressNo ?? "";
                                            expressInfoEntity.ExpressStatus = insuranceWarrantyRecordExpressInfo.ExpressStatus;
                                            expressInfoEntity.SendUserPhone = insuranceWarrantyRecordExpressInfo.SendUserPhone ?? "";
                                            expressInfoEntity.SendUserName = insuranceWarrantyRecordExpressInfo.SendUserName ?? "";
                                            expressInfoEntity.SendUserAddress = insuranceWarrantyRecordExpressInfo.SendUserAddress;
                                            expressInfoEntity.ExpressPrice = insuranceWarrantyRecordExpressInfo.ExpressPrice;
                                            expressInfoEntity.ReceiverUserPhone = insuranceWarrantyRecordExpressInfo.ReceiverUserPhone ?? "";
                                            expressInfoEntity.ReceiverUserName = insuranceWarrantyRecordExpressInfo.ReceiverUserName ?? "";
                                            expressInfoEntity.ReceiverUserAddress = insuranceWarrantyRecordExpressInfo.ReceiverUserAddress ?? "";
                                            expressInfoEntity.PickUpExpressManName = insuranceWarrantyRecordExpressInfo.PickUpExpressManName;
                                            expressInfoEntity.PickUpExpressManPhone = insuranceWarrantyRecordExpressInfo.PickUpExpressManPhone;
                                            responseResult.Success = expressInfoService.UpdateEntities(expressInfoEntity);
                                        }
                                        else
                                        {
                                            insuranceWarrantyRecordExpressInfo.ID = 0;
                                            insuranceWarrantyRecordExpressInfo.ExpressSendByWhoType = (byte)ExpressSendByWhoType.UserSendToPartitionCenter;
                                            insuranceWarrantyRecordExpressInfo.InsuranceWarrantyRecordID = model.ID;
                                            insuranceWarrantyRecordExpressInfo.CreatedBy = CurrentUser.UserAccount;
                                            insuranceWarrantyRecordExpressInfo.CreatedTime = DateTime.Now;
                                            responseResult.Success = expressInfoService.AddEntities(insuranceWarrantyRecordExpressInfo).ID > 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                    if (responseResult.Success)
                    {
                        ts.Complete();
                    }
                    else
                    {
                        ts.Dispose();
                    }
                }
                catch (Exception e)
                {
                    ts.Dispose();
                }
            }
            return Json(responseResult);
        }
        #endregion
    }
}